<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\cost;

use app\enum\ServiceCostEnum;
use app\model\TaskAccountCompareModel;
use app\model\TaskAccountModel;
use app\service\BaseService;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;

final class TaskAccountCompareService extends BaseService
{
    /**
     * 新增task_account_compare表数据.
     * @param TaskAccountModel $model 任务模型
     * @param array $params 表参数
     */
    public static function insertCompareData(TaskAccountModel $model, array $params = []): bool
    {
        if (! $model->getKey()) {
            return self::setError('新增task_account_compare表数据：表task_account数据不存在');
        }
        $params = [
            'task_account_id' => $model->getKey(),
            'account_id' => $model->getAttr('account_id'),
            'advertiser_id' => $model->getAttr('advertiser_id'),
            'media_id' => $model->getAttr('media_id'),
            'stat_date' => $model->getAttr('stat_date'),
            'type' => $model->getAttr('type'),
        ];
        // 校准日期查询
        $compareDates = self::getCompareDate($params['stat_date'], $params['type']);
        if (! $compareDates) {
            return true;
        }
        try {
            foreach ($compareDates as $compareDate) {
                $params['new_stat_date'] = $compareDate;
                $model = new TaskAccountCompareModel();
                $model->setAttrs($params);
                $model->save();
            }
            return true;
        } catch (\Exception $e) {
            return self::setError('插入task_account_compare表失败：' . $e->getMessage());
        }
    }

    /**
     * 更新task_account_compare表数据.
     * @param TaskAccountCompareModel $model 校准表模型
     * @param array $params 表参数
     */
    public static function updateCompareData(TaskAccountCompareModel $model, array $params = []): bool
    {
        if (! $model->getKey()) {
            return self::setError('更新task_account_compare表失败：表数据不存在');
        }
        // 验证字段
        $data = [];
        if (! empty($params['new_task_account_id'])) {
            $data['new_task_account_id'] = $params['new_task_account_id'];
        }
        // 状态验证
        if (! empty($params['status'])) {
            if (! in_array($params['status'], array_keys(ServiceCostEnum::TASK_STATUS_ARR))) {
                return self::setError('状态类型错误');
            }
            $data['status'] = $params['status'];
        }
        if (empty($data)) {
            return self::setError('参数不能为空');
        }
        try {
            $model->setAttrs($params);
            $model->save();
            return true;
        } catch (\Exception $e) {
            return self::setError('更新task_account_compare表失败：' . $e->getMessage());
        }
    }

    /**
     * 删除task_account_compare表数据.
     * @param int $id 表id
     */
    public static function deleteCompareData(int $id = 0): bool
    {
        try {
            $taskModel = (new TaskAccountCompareModel())->find($id);
            if (! $taskModel->getKey()) {
                return self::setError('删除task_account_compare表失败：数据不存在');
            }
            return $taskModel->delete();
        } catch (\Exception $e) {
            return self::setError('删除task_account_compare表失败：' . $e->getMessage());
        }
    }

    /**
     * 获取task_account_compare表模型.
     * @param int $id 表id
     * @return null|array|mixed|Model|TaskAccountCompareModel
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getCompareModel(int $id = 0)
    {
        return (new TaskAccountCompareModel())->find($id);
    }

    /**
     * 获取task_account_compare列表.
     * @param int $mediaId 媒体id
     * @return array|Collection|TaskAccountCompareModel[]
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getCompareList(int $type = 0, int $mediaId = 0, int $date = 0, ...$args)
    {
        $where = [];
        if ($type && $mediaId && $date) {
            $where = [
                ['media_id', '=', $mediaId],
                ['new_stat_date', '=', $date],
                ['type', '=', $type],
            ];
        }
        return (new TaskAccountCompareModel())->where($where)->select();
    }

    /**
     * 根据校准id获取task_account_compare数据.
     * @param int $newTaskAccountId new_task_account_id
     * @return null|array|mixed|Model|TaskAccountCompareModel
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getCompareByNewTaskId(int $newTaskAccountId = 0)
    {
        return (new TaskAccountCompareModel())->where('new_task_account_id', $newTaskAccountId)->find();
    }

    /**
     * 获取对比日期.
     * @param int $date 日期
     * @param int $type 任务类型
     */
    private static function getCompareDate(int $date = 0, int $type = 0): array
    {
        $dates = [];
        $gaps = ServiceCostEnum::COMPARE_GAP[$type];
        foreach ($gaps as $gap) {
            $dates[] = date('Ymd', strtotime("{$date} + {$gap} days"));
        }
        return $dates;
    }
}
